//
//  PEMChallengeAdditionController.swift
//  RelationshipIntegration
//
//  Created by iOS-Czz on 2023/11/16.
//

import UIKit
import ProgressHUD
import BRPickerView

class PEMChallengeAdditionController: PEMBaseViewController {
    var type = 0
    @IBOutlet var picture: UIImageView!
    @IBOutlet var targetTF: UITextField!
    @IBOutlet var dateTF: UITextField!
    var pic:UIImage? = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        setTypeView()
        
        // Do any additional setup after loading the view.
    }
    @IBAction func gotoBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    func setTypeView(){
        let config = HETitleViewConfig()
        config.indicatorViewWidthType = .adaptivelyWidth
        config.bottomLineViewBackgroudColor = .clear
        config.selectedTitleColor = .black
        config.titleColor = .lightGray
        config.indicatorViewBackgroudColor = .black
        let titles = ["Time","Distance","Step number","Energy consumption"]
        
        let titleView = HETitleView.init(frame: CGRect.init(x: 0, y: UIDevice.Navigation_BarHeight() + 30, width: UIScreen.main.bounds.size.width, height: 60),
                                         titles:titles,
                                         titleViewConfig:config)
        view.addSubview(titleView)
        titleView.titleViewClickCallBack = { selectIndex in
            
        }
    }
    @IBAction func clickSaveAction(_ sender: Any) {
        self.view.endEditing(true)
        if self.dateTF.text!.isEmpty {
            ProgressHUD.showError("Please select date of formulation")
            return
        }
        if self.targetTF.text!.isEmpty {
            ProgressHUD.showError("Please enter challenge pbjectives")
            return
        }
        if self.pic == nil {
            ProgressHUD.showError("Please add date success rewards")
            return
        }
        /**
         var date = ""
         var name = ""
         var target = 0.0
         var progress = 0.0
         /// 0 duration 1 distance 2 step 3 energy
         var type = 0
         var rewards = ""
         var completed = false
         var isDefault = true
         */
        let model = PEMChallengeModel()
        model.date = self.dateTF.text!
        model.name = CHALLENGE_NAMES[self.type]
        model.type = self.type
        model.progress = 0.0
        model.rewards = UIImage.saveImageInCache(self.pic!)!
        model.completed = false
        model.target = Double(Int(self.targetTF.text!)!)
        model.isDefault = false
        model.saveToDB()
        let helper = PEMChallengeModel.getUsingLKDBHelper()
        helper.delete(with: PEMChallengeModel.self, where: "isDefault = true")
        ProgressHUD.showSuccess("Challenge addition succeed")
        let delay = 1.5 // 2秒
        let dispatchTime = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
            self.navigationController?.popViewController(animated: true)
        }
    }
    @IBAction func chooseDateAction(_ sender: Any) {
        self.view.endEditing(true)
        let pickerView = BRDatePickerView(pickerMode: .YMD)
        let style = BRPickerStyle(themeColor: THEM_COLOR)
        style.language = "en"
        pickerView.pickerStyle = style
        pickerView.resultBlock = { selectDate,selectValue in
            self.dateTF.text = selectDate?.toString(format: "yyyy.MM.dd")
        }
        pickerView.show()
    }
    
    @IBAction func tapChooseRewardsImae(_ sender: Any) {
        showPickImageVC()
    }
    
}
extension PEMChallengeAdditionController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func showPickImageVC() {
        let photoPickerViewController:UIImagePickerController = UIImagePickerController()
        photoPickerViewController.sourceType = UIImagePickerController.SourceType.photoLibrary
        photoPickerViewController.delegate = self
        photoPickerViewController.modalPresentationStyle = .fullScreen
        self.present(photoPickerViewController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        self.picture.isHidden = false
        self.picture.image = selectedImage
        self.pic = selectedImage
        picker.dismiss(animated: true, completion: nil)
    }
}
